package edu.purdue.cs.aggr;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

public class Main {
	
	private static boolean controller = false;
	private static String IP;
	public static String controllerIP = "ec2-54-235-47-130.compute-1.amazonaws.com";
	private static int port;
	public static int fanout = -1;
	public static int leaves = -1;
	public static String experiment = null;
	
	public static void main (String[] args) throws IOException {
		processArgs(args);
		Node node = null;
		if (controller) {
			populateNodes();
			node = new Controller(IP, port);
	    node.setControllerId(Vertex.createId(controllerIP, port));
		} else {
			node = new VertexManager(IP, port, Vertex.createId(controllerIP, port));
		}
		
		new Thread(node).start();
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private static void populateNodes() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("/home/ec2-user/nodes_aggr_" + "all" +".txt" ));
		String line = null;
		while((line = br.readLine()) != null) {
		  String id = Vertex.createId(line.trim(), port);
		  Controller.nodes.add(id);
			Controller.location.put(id, id);
		}
	}

	private static void processArgs(String[] args) {
		for(int i=0;i<args.length;i++) {
			if(args[i].equals("-ip")) {
			  IP = args[i+1].trim();
			  i++;
			} else if(args[i].equals("-port")) {
			  port = Integer.parseInt(args[i+1].trim());
			  i++;
			} else if(args[i].equals("-controllerip")) {
			  controllerIP = args[i+1].trim();
			  i++;
			} else if(args[i].equals("-fanout")) {
			  fanout = Integer.parseInt(args[i+1].trim());
			  i++;
			} else if(args[i].equals("-leaves")) {
			  leaves = Integer.parseInt(args[i+1].trim());
			  i++;
			} else if(args[i].equals("-experiment")) {
				  experiment = args[i+1].trim();
				  i++;
			} else if (args[i].equals("-type")) {
			  String typeStr = args[i+1];
			  if (typeStr.trim().equals("controller")) {
			    controller = true;
			  } else {
			    controller = false;
			  }
			  i++;
			} else {
				throw new IllegalArgumentException("Unknown parameter");
			}
		} 
	}
}
